import "package:ducafe_ui_core/ducafe_ui_core.dart";
import "package:flutter/material.dart";
import "package:flutter/scheduler.dart";
import "package:flutter_mobx/flutter_mobx.dart";
import "package:go_router/go_router.dart";
import "package:hinge/common/index.dart";
import "package:hinge/common/routers/app_router.dart";
import "package:hinge/common/widgets/custom_dialog.dart";
import "package:hinge/common/widgets/share_bottom_sheet.dart";
import "package:hinge/store/root_store.dart";

class RecommendPage extends StatefulWidget {
  const RecommendPage({super.key});

  // 全局键，用于访问State
  static final GlobalKey<_RecommendPageState> globalKey =
      GlobalKey<_RecommendPageState>();

  @override
  State<RecommendPage> createState() => _RecommendPageState();
}

class _RecommendPageState extends State<RecommendPage>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver, RouteAware {
  final _rootStore = RootStore();
  late TabController _tabController;
  final List<String> _categories = [
    'Strong fragrance',
    'Eau de Toilette',
    'Woody',
  ];

  // 当前用户信息
  UserModel? _currentUser;
  bool _isGuest = false;
  // 记录路由关注状态
  bool _routeIsActive = false;
  // 提供RouteObserver
  // static final RouteObserver<ModalRoute<void>> routeObserver = RouteObserver<ModalRoute<void>>();

  // 为每个分类创建一个PageController
  final Map<String, PageController> _pageControllers = {};

  // 当前每个分类选中的页面索引
  final Map<String, ValueNotifier<int>> _currentPageIndices = {};

  int _selectedCategoryIndex = 0;

  @override
  void initState() {
    super.initState();
    // 添加应用生命周期观察者
    WidgetsBinding.instance.addObserver(this);
    _loadUserInfo();
    _loadRecommendData();

    // 初始化TabController并添加监听
    _tabController = TabController(
      length: _categories.length,
      vsync: this,
      initialIndex: _selectedCategoryIndex,
    );

    _tabController.addListener(() {
      if (_tabController.indexIsChanging ||
          _tabController.index != _selectedCategoryIndex) {
        setState(() {
          _selectedCategoryIndex = _tabController.index;
        });
      }
    });

    // 初始化每个分类的PageController和当前页面索引
    for (var category in _categories) {
      _pageControllers[category] = PageController(keepPage: true);
      _currentPageIndices[category] = ValueNotifier<int>(0);
    }

    // 在下一帧中执行刷新，确保UI已经构建完成
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _refreshPageData();
    });
  }

  // 添加应用生命周期状态监听
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // 应用回到前台时刷新数据
      _refreshPageData();
    }
  }

  // 添加路由状态监听
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route != null) {
      // 订阅路由事件
      AppRouter.routeObserver.subscribe(this, route);
    }
  }

  // 页面变为可见时
  @override
  void didPush() {
    _routeIsActive = true;
    _refreshPageData();
  }

  // 页面重新变为可见时
  @override
  void didPopNext() {
    _routeIsActive = true;
    // 从详情页返回时，只更新状态而不重置索引
    _updateStatusOnly();
  }

  // 页面将被覆盖时
  @override
  void didPushNext() {
    _routeIsActive = false;
  }

  // 页面将被移除时
  @override
  void didPop() {
    _routeIsActive = false;
  }

  // 页面可见性变化时触发刷新
  @override
  void didUpdateWidget(RecommendPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 检查页面是否需要刷新
    _refreshPageData();
  }

  // 加载用户信息
  void _loadUserInfo() {
    _currentUser = UserService.getCurrentUser();
    _isGuest = UserService.isGuestUser();
    setState(() {});
  }

  // 加载推荐数据
  void _loadRecommendData() {
    _rootStore.recommendStore.loadRecommendData();
  }

  // 只更新点赞和收藏状态，不刷新整个页面
  void _updateStatusOnly() {
    // 刷新用户信息（不影响页面索引）
    _loadUserInfo();
    // 只更新点赞和收藏状态
    _rootStore.recommendStore.updateLikeCollectStatusOnly();

    // 不再重新创建PageController，而是使页面刷新
    setState(() {});
  }

  // 刷新页面状态和数据
  void _refreshPageData() {
    // 刷新用户信息
    _loadUserInfo();
    // 刷新推荐数据
    _loadRecommendData();
  }

  // 强制刷新页面的方法，供外部调用
  void forceRefresh() {
    // 重置本地状态并强制刷新
    setState(() {
      // 重新获取用户数据
      _currentUser = UserService.getCurrentUser();
      _isGuest = UserService.isGuestUser();
    });

    // 重新加载推荐数据和用户信息
    _loadUserInfo();
    _loadRecommendData();
  }

  @override
  void dispose() {
    // 取消路由订阅
    AppRouter.routeObserver.unsubscribe(this);
    // 移除观察者
    WidgetsBinding.instance.removeObserver(this);
    _tabController.dispose();

    // 释放所有PageController
    for (var controller in _pageControllers.values) {
      controller.dispose();
    }

    // 释放所有ValueNotifier
    for (var notifier in _currentPageIndices.values) {
      notifier.dispose();
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment(0.50, -0.00),
            end: Alignment(0.50, 1.00),
            colors: [const Color(0xFFA794FD), const Color(0xFFFFEFFA)],
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              _buildHeader(),
              _buildCategoryTabs(),
              Expanded(
                child: TabBarView(
                  controller: _tabController,
                  children:
                      _categories
                          .map((category) => _buildPerfumePageView(category))
                          .toList(),
                ),
              ),
              SizedBox(height: 156.h),
            ],
          ),
        ),
      ),
    );
  }

  // 顶部标题和头像
  Widget _buildHeader() {
    // 不使用Observer，直接获取最新状态并触发setState
    final currentUser = UserService.getCurrentUser();
    final isGuest = UserService.isGuestUser();

    // 确保本地状态与全局同步
    if (_currentUser?.id != currentUser?.id || _isGuest != isGuest) {
      // 如果有变化，调度一个微任务来更新UI
      Future.microtask(() {
        setState(() {
          _currentUser = currentUser;
          _isGuest = isGuest;
        });
      });
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 15.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            'Hot Recommendations',
            style: TextStyle(
              fontSize: 22.sp,
              fontWeight: FontWeight.w700,
              color: Colors.white,
            ),
          ),
          GestureDetector(
            onTap: () => _handleAvatarTap(context),
            child: Stack(
              children: [
                CircleAvatar(
                  radius: 22.r,
                  backgroundImage: AssetImage(
                    currentUser?.avatar ?? AssetsImages.avatar1,
                  ),
                ),
                if (isGuest)
                  Positioned(
                    right: 0,
                    bottom: 0,
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 5.w,
                        vertical: 2.h,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.orange,
                        borderRadius: BorderRadius.circular(4.r),
                      ),
                      child: Text(
                        'Guest',
                        style: TextStyle(
                          fontSize: 10.sp,
                          color: Colors.white,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 处理头像点击事件
  void _handleAvatarTap(BuildContext context) {
    final isGuest = UserService.isGuestUser();

    if (isGuest) {
      // 如果是游客，显示登录提示对话框
      CustomDialog.show(
        context: context,
        title: 'Login Required',
        content:
            'You are currently browsing as a guest. Would you like to log in to access all features?',
        cancelText: 'Cancel',
        confirmText: 'Login',
        onConfirm: () {
          // 使用GoRouter跳转到登录页面
          context.push('/login').then((_) {
            // 从登录页面返回后刷新数据
            _refreshPageData();
          });
        },
      );
    } else {
      // 跳转到个人中心
      context.push('/personal').then((_) {
        // 从个人中心返回后刷新数据
        _refreshPageData();
      });
    }
  }

  // 香水分类标签
  Widget _buildCategoryTabs() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: List.generate(_categories.length, (index) {
          final isSelected = _selectedCategoryIndex == index;
          return GestureDetector(
            onTap: () {
              if (_selectedCategoryIndex != index) {
                setState(() {
                  _selectedCategoryIndex = index;
                });
                _tabController.animateTo(index);
              }
            },
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  _categories[index],
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                    color: isSelected ? Colors.black : Color(0xFF675A99),
                  ),
                ),
                SizedBox(height: 4.h),
                if (isSelected)
                  Container(
                    width: 28.w,
                    height: 4.h,
                    decoration: BoxDecoration(
                      color: Colors.black,
                      borderRadius: BorderRadius.circular(2.r),
                    ),
                  )
                else
                  SizedBox(height: 4.h),
              ],
            ),
          );
        }),
      ),
    );
  }

  // 香水PageView - 可左右滑动
  Widget _buildPerfumePageView(String category) {
    return Observer(
      builder: (_) {
        if (_rootStore.recommendStore.isLoading) {
          return const Center(
            child: CircularProgressIndicator(color: Colors.white),
          );
        }

        // 只显示isRecommend为true且分类匹配的数据
        final filteredPerfumes =
            _rootStore.recommendStore.recommendPerfumes
                .where((p) => p.category == category)
                .toList();

        if (filteredPerfumes.isEmpty) {
          return Center(
            child: Text(
              'No data available',
              style: TextStyle(color: Colors.white, fontSize: 16.sp),
            ),
          );
        }

        return Column(
          children: [
            // 香水展示区
            Expanded(
              child: PageView.builder(
                key: PageStorageKey<String>(category),
                controller: _pageControllers[category],
                physics: const ClampingScrollPhysics(),
                pageSnapping: true,
                itemCount: filteredPerfumes.length,
                onPageChanged: (index) {
                  _currentPageIndices[category]!.value = index;
                },
                itemBuilder: (context, index) {
                  return _buildPerfumeCard(filteredPerfumes[index]);
                },
              ),
            ),

            // 长条分段式指示器
            ValueListenableBuilder<int>(
              valueListenable: _currentPageIndices[category]!,
              builder: (context, currentIndex, _) {
                return Padding(
                  padding: EdgeInsets.only(top: 15.h),
                  child: _buildSegmentedIndicator(
                    itemCount: filteredPerfumes.length,
                    currentIndex: currentIndex,
                  ),
                );
              },
            ),
          ],
        );
      },
    );
  }

  // 长条分段指示器
  Widget _buildSegmentedIndicator({
    required int itemCount,
    required int currentIndex,
  }) {
    // 固定长条长度
    final double indicatorWidth = 100.w;
    // 计算每段宽度
    final double segmentWidth = indicatorWidth / itemCount;

    return SizedBox(
      width: indicatorWidth,
      height: 4.h,
      child: Stack(
        children: [
          // 背景长条 - 浅色
          Container(
            width: indicatorWidth,
            height: 4.h,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.3),
              borderRadius: BorderRadius.circular(2.r),
            ),
          ),

          // 前景指示器 - 深色，随当前页面位置移动
          AnimatedPositioned(
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
            left: currentIndex * segmentWidth,
            child: Container(
              width: segmentWidth,
              height: 4.h,
              decoration: BoxDecoration(
                color: Colors.black,
                borderRadius: BorderRadius.circular(2.r),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 单个香水卡片
  Widget _buildPerfumeCard(PerfumeModel perfume) {
    return Center(
      child: GestureDetector(
        onTap: () {
          context.push('/detail/${perfume.id}');
        },
        child: Container(
          width: 382.41.w,
          height: 552.13.h,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(AssetsImages.cardBg),
              fit: BoxFit.contain,
            ),
          ),
          child: Align(
            alignment: Alignment.bottomCenter,
            child: Stack(
              children: [
                // 香水图片作为背景
                Container(
                  width: 360.w,
                  height: 528.h,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(16.r),
                    image: DecorationImage(
                      image: AssetImage(perfume.url),
                      fit: BoxFit.cover,
                    ),
                  ),
                  child: Stack(
                    children: [
                      // 左侧用户信息
                      Positioned(
                        left: 16.w,
                        bottom: 15.h,
                        child: Observer(
                          builder: (_) {
                            // 在Observer内部获取最新的用户数据
                            final user = UserService.getUserById(
                              perfume.userId,
                            );

                            return GestureDetector(
                              onTap: () {
                                // 只有在用户不为空时才跳转
                                if (user != null) {
                                  // 如果是当前用户，直接跳转到个人中心
                                  final currentUser =
                                      UserService.getCurrentUser();
                                  if (currentUser != null &&
                                      user.id == currentUser.id) {
                                    context.push('/personal');
                                  } else {
                                    // 否则跳转到指定用户的个人中心
                                    context.push('/personal/${user.id}');
                                  }
                                }
                              },
                              child: Container(
                                width: 129.w,
                                height: 50.h,
                                decoration: BoxDecoration(
                                  image: DecorationImage(
                                    image: AssetImage(AssetsImages.cardLeft),
                                    fit: BoxFit.fill,
                                  ),
                                ),
                                padding: EdgeInsets.symmetric(
                                  horizontal: 12.w,
                                  vertical: 8.h,
                                ),
                                child: Row(
                                  children: [
                                    CircleAvatar(
                                      radius: 18.r,
                                      backgroundImage:
                                          user != null
                                              ? AssetImage(user.avatar)
                                              : null,
                                    ),
                                    SizedBox(width: 6.w),
                                    Text(
                                      user?.nickname ?? '',
                                      style: TextStyle(
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.w600,
                                        color: Colors.black87,
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                      // 右侧操作按钮
                      Positioned(
                        right: 16.w,
                        bottom: 15.h,
                        child: Container(
                          width: 204.w,
                          height: 50.h,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage(AssetsImages.cardRight),
                              fit: BoxFit.fill,
                            ),
                          ),
                          padding: EdgeInsets.symmetric(
                            horizontal: 6.w,
                            vertical: 8.h,
                          ),
                          child: Row(
                            children: [
                              SizedBox(width: 5.w),
                              Expanded(
                                child: IconButton(
                                  iconSize: 24.w,
                                  padding: EdgeInsets.zero,
                                  constraints: const BoxConstraints(),
                                  icon: Observer(
                                    builder: (_) {
                                      final isLiked = _rootStore.recommendStore
                                          .isPerfumeLiked(perfume.id);
                                      return AnimatedSwitcher(
                                        duration: const Duration(
                                          milliseconds: 300,
                                        ),
                                        transitionBuilder: (child, animation) {
                                          return ScaleTransition(
                                            scale: animation,
                                            child: child,
                                          );
                                        },
                                        child: Icon(
                                          isLiked
                                              ? IconFont.likeFill
                                              : IconFont.like,
                                          key: ValueKey<String>(
                                            "like_$isLiked",
                                          ),
                                          color:
                                              isLiked
                                                  ? Color(0xFFDF6CCB)
                                                  : Colors.black87,
                                        ),
                                      );
                                    },
                                  ),
                                  onPressed: () => _handleLike(perfume.id),
                                ),
                              ),
                              Expanded(
                                child: IconButton(
                                  iconSize: 24.w,
                                  padding: EdgeInsets.zero,
                                  constraints: const BoxConstraints(),
                                  icon: Observer(
                                    builder: (_) {
                                      final isCollected = _rootStore
                                          .recommendStore
                                          .isPerfumeCollected(perfume.id);
                                      return AnimatedSwitcher(
                                        duration: const Duration(
                                          milliseconds: 300,
                                        ),
                                        transitionBuilder: (child, animation) {
                                          return ScaleTransition(
                                            scale: animation,
                                            child: child,
                                          );
                                        },
                                        child: Icon(
                                          isCollected
                                              ? IconFont.goodFill
                                              : IconFont.good,
                                          key: ValueKey<String>(
                                            "collect_$isCollected",
                                          ),
                                          color:
                                              isCollected
                                                  ? Color(0xFFDF6CCB)
                                                  : Colors.black87,
                                        ),
                                      );
                                    },
                                  ),
                                  onPressed: () => _handleCollect(perfume.id),
                                ),
                              ),
                              Expanded(
                                child: IconButton(
                                  iconSize: 24.w,
                                  padding: EdgeInsets.zero,
                                  constraints: const BoxConstraints(),
                                  icon: Icon(IconFont.share),
                                  onPressed: () => _handleShare(perfume),
                                ),
                              ),
                              Expanded(
                                child: IconButton(
                                  iconSize: 24.w,
                                  padding: EdgeInsets.zero,
                                  constraints: const BoxConstraints(),
                                  icon: Icon(IconFont.info),
                                  onPressed: () {
                                    showReportBottomSheet(context);
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 处理点赞操作
  void _handleLike(int perfumeId) async {
    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || UserService.isGuestUser()) {
      _showLoginRequiredDialog('Like');
      return;
    }
    await _rootStore.recommendStore.likePerfume(perfumeId);
  }

  // 处理收藏操作
  void _handleCollect(int perfumeId) async {
    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || UserService.isGuestUser()) {
      _showLoginRequiredDialog('Collect');
      return;
    }
    await _rootStore.recommendStore.collectPerfume(perfumeId);
  }

  // 处理分享操作
  void _handleShare(PerfumeModel perfume) async {
    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || UserService.isGuestUser()) {
      _showLoginRequiredDialog('share');
      return;
    }

    // 显示分享弹窗
    showShareBottomSheet(
      context: context,
      content: perfume, // 传递香水卡片数据
      isVideo: false, // 这是香水卡片而非视频
    );
  }

  // 显示登录提示对话框
  void _showLoginRequiredDialog(String action) {
    CustomDialog.show(
      context: context,
      title: 'Login Required',
      content:
          'You need to login to $action this item. Would you like to login now?',
      cancelText: 'Cancel',
      confirmText: 'Login',
      onConfirm: () {
        context.push('/login').then((_) {
          // 从登录页面返回后刷新数据
          _refreshPageData();
        });
      },
    );
  }
}
